package com.zhentao.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhentao.util.IdentityAuthResponse;
import com.zhentao.util.Result;
import com.zhentao.pojo.User;
import com.zhentao.service.UserService;
import com.zhentao.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import okhttp3.*;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.StringUtils;

import java.io.IOException;

@RestController
@RequestMapping("/rz")
@CrossOrigin(origins = "*") // 允许跨域访问
public class Controller {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/rz")
    public Result rz(@RequestParam String name, @RequestParam String card, @RequestParam(required = false) String userId) throws IOException {
        // 参数验证
        if (!StringUtils.hasText(name) || !StringUtils.hasText(card)) {
            return Result.ERROR("姓名和身份证号不能为空");
        }

        // 简单的身份证号格式验证
        if (card.length() != 18) {
            return Result.ERROR("身份证号格式不正确");
        }

        System.out.println("收到实名认证请求 - 姓名: " + name + ", 身份证号: " + card.substring(0, 6) + "****" + card.substring(14) + ", 用户ID: " + userId);
        String url = "https://idenauthen.market.alicloudapi.com/idenAuthentication";
        // 获取appCode链接：https://market.console.aliyun.com/
        String appCode = "dad0d868eb7443359f3930196e975087";
        RequestBody formBody = new FormBody.Builder().
                add("name", name).add("idNo", card).build();
        Request request = new Request.Builder().url(url).
                addHeader("Authorization", "APPCODE " + appCode).post(formBody).build();

        Call call = new OkHttpClient().newCall(request);
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e) {
            System.out.println("execute failed, message:" + e.getMessage());
            return Result.ERROR("请求失败: " + e.getMessage());
        }

        assert response != null;
        if (!response.isSuccessful()) {
            // 状态码为403时一般是套餐包用尽，需续购；
            // 注意：续购不会改变秘钥（appCode），仅增加次数
            // 续购链接：https://market.aliyun.com/products/57000002/cmapi025518.html
            System.out.println("request failed----" + "返回状态码" + response.code()  +
                    ",message:" + response.message());
            return Result.ERROR("API请求失败，状态码: " + response.code());
        }
        
        String responseString = response.body().string();
        System.out.println(responseString);
        
        try {
            // 将JSON字符串转换为实体类对象
            ObjectMapper objectMapper = new ObjectMapper();
            IdentityAuthResponse authResponse = objectMapper.readValue(responseString, IdentityAuthResponse.class);

            // 如果认证成功且提供了用户ID，则保存实名信息到数据库
            if ("0000".equals(authResponse.getRespCode()) && StringUtils.hasText(userId)) {
                try {
                    saveVerificationInfo(userId, name, card);
                    System.out.println("实名认证信息已保存到数据库，用户ID: " + userId);
                } catch (Exception saveException) {
                    System.out.println("保存实名认证信息失败: " + saveException.getMessage());
                    // 注意：这里不返回错误，因为认证本身是成功的
                }
            }

            return Result.OK(authResponse);
        } catch (Exception e) {
            System.out.println("解析响应失败: " + e.getMessage());
            return Result.ERROR("解析响应失败: " + e.getMessage());
        }
    }

    /**
     * 查询用户实名认证状态
     *
     * @param userId 用户ID
     * @return 认证状态信息
     */
    @GetMapping("/status")
    public Result getVerificationStatus(@RequestParam String userId) {
        if (!StringUtils.hasText(userId)) {
            return Result.ERROR("用户ID不能为空");
        }

        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", userId);
            User user = userMapper.selectOne(queryWrapper);

            if (user == null) {
                return Result.ERROR("用户不存在");
            }

            // 检查实名认证状态：captcha字段存储姓名，correct_captcha字段存储身份证号
            // 只有当两个字段都不为空且不为空字符串时，才认为已实名认证
            String realName = user.getCaptcha();
            String idCard = user.getCorrectCaptcha();
            boolean isVerified = StringUtils.hasText(realName) && StringUtils.hasText(idCard);

            System.out.println("获取认证状态详情 - 用户ID: " + userId +
                             ", 姓名字段: " + (StringUtils.hasText(realName) ? "有数据" : "无数据") +
                             ", 身份证字段: " + (StringUtils.hasText(idCard) ? "有数据" : "无数据") +
                             ", 认证状态: " + (isVerified ? "已认证" : "未认证"));

            if (isVerified) {
                // 返回认证信息（隐藏敏感信息）
                String maskedIdCard = idCard.substring(0, 6) + "****" + idCard.substring(14);

                return Result.OK(new java.util.HashMap<String, Object>() {{
                    put("isVerified", true);
                    put("realName", realName);
                    put("idCard", maskedIdCard);
                    put("message", "已实名认证");
                    put("verifyDate", "2024-01-01"); // 这里可以添加认证时间字段
                }});
            } else {
                return Result.OK(new java.util.HashMap<String, Object>() {{
                    put("isVerified", false);
                    put("message", "未实名认证");
                    put("realName", null);
                    put("idCard", null);
                    put("verifyDate", null);
                }});
            }
        } catch (Exception e) {
            System.out.println("查询实名认证状态失败: " + e.getMessage());
            return Result.ERROR("查询失败: " + e.getMessage());
        }
    }

    /**
     * 检查实名认证状态（用于状态卡片显示）
     * @param userId 用户ID（可选参数，如果不提供则从session获取）
     */
    @GetMapping("/check-status")
    public Result checkVerificationStatus(@RequestParam(required = false) String userId) {
        try {
            System.out.println("=== 收到实名认证状态检查请求 ===");
            System.out.println("请求参数 - 用户ID: " + userId);

            // 如果没有提供userId，这里应该从session或token中获取当前用户ID
            // 目前为了演示，如果没有userId就返回模拟数据
            if (!StringUtils.hasText(userId)) {
                java.util.Map<String, Object> statusData = new java.util.HashMap<>();
                statusData.put("isVerified", false);
                statusData.put("verifyDate", null);
                statusData.put("message", "请先提供用户ID");

                System.out.println("❌ 未提供用户ID，返回未认证状态");
                System.out.println("返回数据: " + statusData);
                return Result.OK(statusData);
            }

            // 查询用户实名认证状态
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", userId);
            User user = userMapper.selectOne(queryWrapper);

            if (user == null) {
                java.util.Map<String, Object> statusData = new java.util.HashMap<>();
                statusData.put("isVerified", false);
                statusData.put("verifyDate", null);
                statusData.put("message", "用户不存在");

                System.out.println("用户不存在，用户ID: " + userId);
                return Result.OK(statusData);
            }

            // 检查实名认证状态：captcha字段存储姓名，correct_captcha字段存储身份证号
            // 只有当两个字段都不为空且不为空字符串时，才认为已实名认证
            String realName = user.getCaptcha();
            String idCard = user.getCorrectCaptcha();

            boolean isVerified = StringUtils.hasText(realName) && StringUtils.hasText(idCard);

            java.util.Map<String, Object> statusData = new java.util.HashMap<>();
            statusData.put("isVerified", isVerified);
            statusData.put("verifyDate", isVerified ? "2024-01-01" : null); // 这里可以添加实际的认证时间字段
            statusData.put("message", isVerified ? "已实名认证" : "未实名认证");

            // 如果已认证，添加脱敏后的认证信息
            if (isVerified) {
                statusData.put("realName", realName);
                statusData.put("idCard", idCard.substring(0, 6) + "****" + idCard.substring(14));
            }

            System.out.println("实名认证状态检查 - 用户ID: " + userId +
                             ", 姓名字段: " + (StringUtils.hasText(realName) ? "有数据" : "无数据") +
                             ", 身份证字段: " + (StringUtils.hasText(idCard) ? "有数据" : "无数据") +
                             ", 认证状态: " + (isVerified ? "已认证" : "未认证"));

            return Result.OK(statusData);

        } catch (Exception e) {
            System.out.println("检查实名认证状态异常: " + e.getMessage());
            e.printStackTrace();
            return Result.ERROR("检查实名认证状态失败: " + e.getMessage());
        }
    }

    /**
     * 保存实名认证信息到数据库
     *
     * @param userId 用户ID
     * @param realName 真实姓名
     * @param idCard 身份证号
     */
    private void saveVerificationInfo(String userId, String realName, String idCard) {
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            System.out.println("用户不存在，ID: " + userId);
            return;
        }

        // 检查是否已经实名认证过（检查captcha字段是否有姓名，correct_captcha字段是否有身份证号）
        if (StringUtils.hasText(user.getCaptcha()) && StringUtils.hasText(user.getCorrectCaptcha())) {
            System.out.println("用户已经实名认证过，不再重复保存。姓名: " + user.getCaptcha() +
                             ", 身份证号: " + user.getCorrectCaptcha().substring(0, 6) + "****" +
                             user.getCorrectCaptcha().substring(14));
            return;
        }

        // 更新用户实名认证信息
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setCaptcha(realName);         // 真实姓名保存到captcha字段
        updateUser.setCorrectCaptcha(idCard);    // 身份证号保存到correct_captcha字段

        int result = userMapper.update(updateUser, queryWrapper);
        if (result > 0) {
            System.out.println("实名认证信息保存成功 - 姓名: " + realName +
                             ", 身份证号: " + idCard.substring(0, 6) + "****" + idCard.substring(14));
        } else {
            System.out.println("实名认证信息保存失败");
        }
    }
}
